package com.ddwl.order.service;

import com.ddwl.common.constant.BaseEnum;
import com.ddwl.common.exception.ParamException;
import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.order.dao.OrderPhaseDao;
import com.ddwl.order.dao.model.OrderPhase;
import com.ddwl.schema.vo.order.OrderPhaseVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;

/**
 * 类OrderPhaseServer.java的实现描述：订单分段支付处理
 *
 * @author zach
 * @Date :2020-06-02 16:38.
 */
@Service
public class OrderPhaseServer {

    @Resource
    private OrderPhaseDao orderPhaseDao;

    public void completePayment(String phaseId){
        OrderPhase orderPhase = orderPhaseDao.selectByPrimaryKey(phaseId);
        ParamException.isNull(orderPhase);
        ParamException.isFalse(BaseEnum.StatusEnum.DISABLE.getCode().equals(orderPhase.getStatus()));
        OrderPhase update = new OrderPhase();
        update.setId(phaseId);
        update.setStatus(BaseEnum.StatusEnum.ENABLE.getCode());
        orderPhaseDao.updateByPrimaryKeySelective(update);
    }

    @Deprecated
    public void completePaymentNew(String phaseId){
        OrderPhase orderPhase = orderPhaseDao.selectByPrimaryKey(phaseId);
        ParamException.isNull(orderPhase);
        ParamException.isNull(orderPhase.getMasterOrderId());
        ParamException.isFalse(BaseEnum.StatusEnum.DISABLE.getCode().equals(orderPhase.getStatus()));
        OrderPhase update = new OrderPhase();
        update.setStatus(BaseEnum.StatusEnum.ENABLE.getCode());
        orderPhaseDao.updateCompletePayment(update,orderPhase.getMasterOrderId());
    }



    /**
     * 查询订单支付阶梯
     * @param orderId
     * @return
     */
    public List<OrderPhaseVo> getOrderPhase(String orderId){
        OrderPhase orderPhase = new OrderPhase();
        orderPhase.setOrderNo(orderId);
        return BeanConverUtils.convertBeanList(orderPhaseDao.select(orderPhase),OrderPhaseVo.class);
    }

    /**
     * 查询订单支付阶梯
     * @param orderIds
     * @return
     */
    public List<OrderPhaseVo> getOrderPhase(List<String> orderIds){
        return BeanConverUtils.convertBeanList(orderPhaseDao.queryOrderPhases(orderIds),OrderPhaseVo.class);
    }

    /**
     * 获取
     * @param orderId
     * @return
     */
    public OrderPhaseVo getNoPayPhase(String orderId){
        List<OrderPhaseVo> orderPhase = getOrderPhase(orderId);
        orderPhase.sort(Comparator.comparing(OrderPhaseVo::getPhase));
        for(OrderPhaseVo orderPhaseVo : orderPhase){
            if (BaseEnum.StatusEnum.DISABLE.getCode().equals(orderPhaseVo.getStatus())){
                return orderPhaseVo;
            }
        }
        return null;
    }

}
